package com.mall.user.controller;

import com.mall.common.util.JsonResult;
import com.mall.user.common.exception.BusinessException;
import com.mall.user.common.response.ResultCode;
import com.mall.user.constant.UserConstant;
import com.mall.user.model.dto.address.AddressAddRequest;
import com.mall.user.model.dto.address.AddressUpdateRequest;
import com.mall.user.model.entity.User;
import com.mall.user.model.vo.AddressVO;
import com.mall.user.service.AddressService;
import com.mall.user.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private AddressService addressService;

    @Resource
    private UserService userService;

    /**
     * 检查用户是否有权限操作
     */
    private void checkAddressPermission(User currentUser, Long targetUserId) {
        if (currentUser == null) {
            throw new BusinessException(ResultCode.UNAUTHORIZED, "用户未登录");
        }
        
        // 如果是管理员，允许操作任何用户的地址
        if (UserConstant.ADMIN_ROLE.equals(currentUser.getUser_type())) {
            return;
        }
        
        // 如果不是管理员，只能操作自己的地址
        if (!currentUser.getId().equals(targetUserId)) {
            throw new BusinessException(ResultCode.FORBIDDEN, "无权限操作他人地址");
        }
    }

    /**
     * 添加地址
     */
    @PostMapping("/add")
    public JsonResult<String> addAddress(@Valid @RequestBody AddressAddRequest addressAddRequest,
                                        HttpServletRequest request) {
        if (addressAddRequest == null) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址信息不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkAddressPermission(loginUser, loginUser != null ? loginUser.getId() : null);
        
        String addressId = addressService.addAddress(loginUser.getId(), addressAddRequest);
        return JsonResult.success(addressId);
    }

    /**
     * 更新地址
     */
    @PutMapping("/update")
    public JsonResult<Boolean> updateAddress(@Valid @RequestBody AddressUpdateRequest addressUpdateRequest,
                                           HttpServletRequest request) {
        if (addressUpdateRequest == null) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址信息不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkAddressPermission(loginUser, loginUser != null ? loginUser.getId() : null);
        
        boolean result = addressService.updateAddress(loginUser.getId(), addressUpdateRequest);
        return JsonResult.success(result);
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/delete/{addressId}")
    public JsonResult<Boolean> deleteAddress(@PathVariable String addressId,
                                           HttpServletRequest request) {
        if (StringUtils.isBlank(addressId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址ID不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkAddressPermission(loginUser, loginUser != null ? loginUser.getId() : null);
        
        boolean result = addressService.deleteAddress(loginUser.getId(), addressId);
        return JsonResult.success(result);
    }

    /**
     * 获取用户所有地址
     */
    @GetMapping("/list")
    public JsonResult<List<AddressVO>> getUserAddresses(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkAddressPermission(loginUser, loginUser != null ? loginUser.getId() : null);
        
        List<AddressVO> addresses = addressService.getUserAddresses(loginUser.getId());
        return JsonResult.success(addresses);
    }

    /**
     * 获取特定地址
     */
    @GetMapping("/get/{addressId}")
    public JsonResult<AddressVO> getAddressById(@PathVariable String addressId,
                                              HttpServletRequest request) {
        if (StringUtils.isBlank(addressId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址ID不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkAddressPermission(loginUser, loginUser != null ? loginUser.getId() : null);
        
        AddressVO address = addressService.getAddressById(loginUser.getId(), addressId);
        return JsonResult.success(address);
    }

    /**
     * 通过用户ID获取地址
     */
    @GetMapping("/get/{userId}/{addressId}")
    public JsonResult<AddressVO> getAddressById(
            @PathVariable("userId") Long userId,
            @PathVariable("addressId") String addressId) {

        if (StringUtils.isBlank(addressId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址ID不能为空");
        }
        if (userId == null) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }
        AddressVO address = addressService.getAddressById(userId, addressId);
        return JsonResult.success(address);
    }

    /**
     * 获取默认地址
     */
    @GetMapping("/get/default")
    public JsonResult<AddressVO> getDefaultAddress(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkAddressPermission(loginUser, loginUser != null ? loginUser.getId() : null);
        
        AddressVO defaultAddress = addressService.getDefaultAddress(loginUser.getId());
        return JsonResult.success(defaultAddress);
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/default/{addressId}")
    public JsonResult<Boolean> setDefaultAddress(@PathVariable String addressId, 
                                               HttpServletRequest request) {
        if (StringUtils.isBlank(addressId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址ID不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkAddressPermission(loginUser, loginUser != null ? loginUser.getId() : null);
        
        boolean result = addressService.setDefaultAddress(loginUser.getId(), addressId);
        return JsonResult.success(result);
    }
}
